from typing import Dict, Any, List
import json
import os
from config.FileHandle import COMMON_TOOLS_PATH

from fastapi import APIRouter, HTTPException

router = APIRouter(prefix="/api/common/tools", tags=["CommonTools"])


@router.get("/list", response_model=Dict[str, List[Dict[str, Any]]])
async def get_tools_list():
    """获取所有工具列表，按类型分类"""
    try:
        if not os.path.exists(COMMON_TOOLS_PATH):
            return {
                "quickTools": [],
                "MCPTools": [],
                "workflowComponents": []
            }
            
        with open(COMMON_TOOLS_PATH, 'r', encoding='utf-8') as f:
            tools_data = json.load(f)
            
        # 确保返回的数据包含所有分类
        return {
            "quickTools": tools_data.get("quickTools", []),
            "MCPTools": tools_data.get("MCPTools", []),
            "workflowComponents": tools_data.get("workflowComponents", [])
        }
    except Exception as e:
        raise HTTPException(status_code=500, detail=str(e))


@router.post("/{tool_type}", response_model=Dict[str, Any])
async def add_tool(tool_type: str, tool: Dict[str, Any]):
    """添加工具到指定分类"""
    try:
        if tool_type not in ["quickTools", "MCPTools", "workflowComponents"]:
            raise HTTPException(status_code=400, detail="无效的工具类型")
            
        # 读取现有工具列表
        tools_data = {}
        if os.path.exists(COMMON_TOOLS_PATH):
            with open(COMMON_TOOLS_PATH, 'r', encoding='utf-8') as f:
                tools_data = json.load(f)
                
        # 确保工具类型列表存在
        if tool_type not in tools_data:
            tools_data[tool_type] = []
            
        # 添加新工具
        tools_data[tool_type].append(tool)
        
        # 保存更新后的工具列表
        with open(COMMON_TOOLS_PATH, 'w', encoding='utf-8') as f:
            json.dump(tools_data, f, ensure_ascii=False, indent=2)
            
        return {"message": "工具添加成功", "tool": tool}
    except Exception as e:
        raise HTTPException(status_code=500, detail=str(e))


@router.delete("/{tool_type}/{tool_id}")
async def delete_tool(tool_type: str, tool_id: str):
    """从指定分类中删除工具"""
    try:
        if tool_type not in ["quickTools", "MCPTools", "workflowComponents"]:
            raise HTTPException(status_code=400, detail="无效的工具类型")
            
        # 读取现有工具列表
        if not os.path.exists(COMMON_TOOLS_PATH):
            raise HTTPException(status_code=404, detail="工具列表不存在")
            
        with open(COMMON_TOOLS_PATH, 'r', encoding='utf-8') as f:
            tools_data = json.load(f)
            
        # 检查工具类型是否存在
        if tool_type not in tools_data:
            raise HTTPException(status_code=404, detail=f"工具类型 {tool_type} 不存在")
            
        # 查找并删除工具
        tools = tools_data[tool_type]
        original_length = len(tools)
        tools_data[tool_type] = [tool for tool in tools if tool.get("id") != tool_id]
        
        if len(tools_data[tool_type]) == original_length:
            raise HTTPException(status_code=404, detail=f"未找到ID为 {tool_id} 的工具")
            
        # 保存更新后的工具列表
        with open(COMMON_TOOLS_PATH, 'w', encoding='utf-8') as f:
            json.dump(tools_data, f, ensure_ascii=False, indent=2)
            
        return {"message": "工具删除成功"}
    except Exception as e:
        raise HTTPException(status_code=500, detail=str(e))
